package org.example.reggie.upload;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.example.reggie.result.ResultData;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

/**
 * 文件上传 下载
 */
@RestController
@RequestMapping("/common")
public class UploadController {

    //保存路径
    @Value("${reggie.path}")
    private String basePath;


    /**
     * 文件上传利用NIO
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public ResultData<String> upload(MultipartFile file){
        //获取图片名称
        String fileName = file.getOriginalFilename();
        //获取后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //生成随机数
        String uuid = UUID.randomUUID().toString();
        //拼接新的名字
        String newFileName = fileName+uuid+suffix;
        //判断路径是否存在
        File file1 = new File(basePath);
        if(!file1.exists()){
            file1.mkdirs();
        }
        //拼接完整路径
        String imageUrl = basePath+newFileName;
        try {
            //上传
            file.transferTo(new File(imageUrl));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return ResultData.success(newFileName);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        File file = new File(basePath + name);
        FileInputStream inputStream =null;
        ServletOutputStream outputStream =null;
        try {
            //读取图片 放到输入流
            inputStream =  new FileInputStream(file);
            //获取输出流对象
            outputStream = response.getOutputStream();
            //设置输出类型
            response.setContentType("image/jpeg");
            //把输入流 放到输出流 返回到页面
            //读取标志
           int  let =0;
           //每次都多少
            byte[] bytes = new byte[1024];
            while((let = inputStream.read(bytes)) != -1){
                //填充到输出流中
                outputStream.write(bytes,0,let);
                outputStream.flush();
            }
            outputStream.close();
            inputStream.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } finally{
            if( null != outputStream){
                outputStream.close();
            }
            if(null != inputStream){
                inputStream.close();
            }
        }
    }
}
